package web.common;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

import java.io.File;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.HashMap;

import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: duanbin
 * Date: 2007-8-21
 * Time: 22:30:13
 * To change this template use File | Settings | File Templates.
 */
public abstract class BaseGenerator {
    protected Configuration cfg;
    protected final Logger logger = Logger.getLogger(this.getClass());

    public BaseGenerator() {
        try {
            cfg = getConfiguration(CodeEngineConfig.getTemplateDir());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract String getFileName(String name);
    protected abstract void prepareData(Map root, String name);
    protected void afterGenerate(String name){}

    private Map prepareAllData(String name) {
        Map root = new HashMap();
        prepareData(root,name);
        root.put("package", CodeEngineConfig.getBasePackage());
        root.put("appPkg", CodeEngineConfig.getAppPackage());
        return root;
    }

    public void generate() {
        try {
            for(String name : CodeEngineConfig.getControllerNames()){
                String fileName = CodeEngineConfig.getDistDir() + "/" + getFileName(name);
                File dist = new File(fileName);
                FileOutputStream fos = new FileOutputStream(dist);
                Writer out = new OutputStreamWriter(fos);

    //            Writer out2 = new OutputStreamWriter(System.out);
                getTemplate(name).process(prepareAllData(name), out);

                out.flush();
                out.close();
                logger.info("Generated File: "  + fileName);
                afterGenerate(name);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Configuration getConfiguration(String tempDir) throws Exception {
        Configuration cfg = new Configuration();
        // Specify the data source where the template files come from.
        // Here I set a file directory for it:
        cfg.setDirectoryForTemplateLoading(
                new File(tempDir));
        // Specify how templates will see the data model. This is an advanced topic...
        // but just use this:
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        return cfg;
    }

    protected Template getTemplate(String name) throws Exception {
        return cfg.getTemplate(CodeEngineConfig.getControllerTemplate(name));
    }
}
